package com.wecan.data.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.wecan.data.mybatis.AppIdentifierGenerator;
import com.wecan.data.mybatis.BatisMetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @Author liuzhihao
 * @Date 2022.01.11
 * @Version 1.0.0
 * @Description 数据层配置
 */
@Configuration
@Slf4j
public class DataConfig {

    @PostConstruct
    public void postConstruct() {
        log.info("[APP] -| Data Config init");
    }

    private DbType parseDbType() {
        return DbType.MYSQL;
    }

    /**
     * 防止 修改与删除时对全表进行操作
     *
     * @return {@link MybatisPlusInterceptor}
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(parseDbType()));
        BlockAttackInnerInterceptor blockAttackInnerInterceptor = new BlockAttackInnerInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(blockAttackInnerInterceptor);
        log.info("[APP] |- 初始化分页器和防止修改和删除");
        return mybatisPlusInterceptor;
    }

    @Bean
    public IdentifierGenerator identifierGenerator() {
        AppIdentifierGenerator appIdentifierGenerator = new AppIdentifierGenerator();
        log.info("[APP] |- 初始化id生成器");
        return appIdentifierGenerator;
    }

    @Bean
    public MetaObjectHandler metaObjectHandler() {
        BatisMetaObjectHandler batisMetaObjectHandler = new BatisMetaObjectHandler();
        log.info("[APP] |- 初始化mybatis自动填充器");
        return batisMetaObjectHandler;
    }
}
